<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@include file="/WEB-INF/webpage/common/taglibs.jspf"%>
<!DOCTYPE html>
<html>
  <head>
  	<title>web 文件管理</title>
    <meta name="decorator" content="form"/>
    <html:css name="bootstrap-fileinput"/>
    <html:css name="simditor"/>
    <%--webuploader--%>
    <link type="text/css" rel="stylesheet" href="${staticPath }/vendors/webuploader/webuploader.css"/>
	<link type="text/css" rel="stylesheet" href="${staticPath}/vendors/webuploader/drag/style.css" />
	<link type="text/css" rel="stylesheet" href="${staticPath}/vendors/webuploader/cropper/css/cropper.css" />
	<link type="text/css" rel="stylesheet" href="${staticPath}/vendors/webuploader/cropper/css/style.css" />
	<script type="text/javascript" src="${staticPath}/vendors/webuploader/cropper/js/cropper.js" ></script>
	<script type="text/javascript" src="${staticPath}/vendors/webuploader/webuploader.min.js"></script>
    <%-- <script type="text/javascript" src="${staticPath }/vendors/webuploader/webuploader.nolog.min.js"></script> --%>
    <%-- <script type="text/javascript" src="${staticPath }/common/js/webuploader.js"></script> --%>
    <html:css  name="syntaxhighlighter"/>
</head>
<body>
	<%-- <div class="portlet-body">
		<p>文件上传标签</p>
		<html:display></html:display>
		<form:webuploader path="file" nested="false"/>
	</div> --%>
	<div id="wrapper">
		<!--拖拽上传-->
        <div id="container">
            <!--头部，相册选择和格式选择-->
            <div id="uploader">
                <div id="queueList" class="queueList">
                    <div id="dndArea" class="placeholder">
                        <div id="filePicker"></div>
                        <p>或将照片拖到这里，单次最多可选300张</p>
                    </div>
                </div>
                <div id="statusBar" class="statusBar" style="display:none;">
                    <div id="progress" class="progress">
                        <span id="text" class="text">0%</span>
                        <span id="percentage" class="percentage"></span>
                    </div><div id="info" class="info"></div>
                    <div class="btns">
                        <div id="filePicker2"></div><div id="uploadBtn" class="uploadBtn">开始上传</div>
                    </div>		                    
                </div>
            </div>
       </div>
  </div>
  <script type="text/javascript">
			(function( $ ){
				$(function(){
					//定义当前使用的WebUploader，防止一个界面出现两个上传时冲突
					var webUpload = WebUploader;
					
					var $wrap = $('#uploader'),
			            // 图片容器
			            $queue = $( '<ul class="filelist"></ul>' ).appendTo( $wrap.find( '#queueList' ) ),
			            // 状态栏，包括进度和控制按钮
			            $statusBar = $wrap.find( '#statusBar' ),
			            // 文件总体选择信息。
			            $info = $statusBar.find( '#info' ),
			            // 上传按钮
			            $upload = $wrap.find( '#uploadBtn' ),
			            // 没选择文件之前的内容。
			            $placeHolder = $wrap.find( '#dndArea' ),
			            $progress = $statusBar.find( '#progress' ).hide(),
			            // 添加的文件数量
			            fileCount = 0,
			            // 添加的文件总大小
			            fileSize = 0,
			            // 优化retina, 在retina下这个值是2
			            ratio = window.devicePixelRatio || 1,
			            // 缩略图大小
			            thumbnailWidth = 110 * ratio,
			            thumbnailHeight = 110 * ratio,
			            // 可能有pedding, ready, uploading, confirm, done.
			            state = 'pedding',
			            // 所有文件的进度信息，key为file id
			            percentages = {};
					var fileMd5 = null,
						count = 0,
						fileName = null;
					var filesArr = new Array();
					/**检测浏览器过程开始*/
					
					// 判断浏览器是否支持图片的base64
					var isSupportBase64 = ( function() {
			            var data = new Image();
			            var support = true;
			            data.onload = data.onerror = function() {
			                if( this.width != 1 || this.height != 1 ) {
			                    support = false;
			                }
			            }
			            data.src = "";
			            return support;
			        } )();
			        
			        // 检测是否已经安装flash，检测flash的版本
			        var flashVersion = ( function() {
			            var version;
			            try {
			                version = navigator.plugins[ 'Shockwave Flash' ];
			                version = version.description;
			            } catch ( ex ) {
			                try {
			                    version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
			                            .GetVariable('$version');
			                } catch ( ex2 ) {
			                    version = '0.0';
			                }
			            }
			            version = version.match( /\d+/g );
			            return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 );
			        } )();
			        
			        //检测是否支持转换
			        var supportTransition = (function(){
			            var s = document.createElement('p').style,
			                r = 'transition' in s ||
			                        'WebkitTransition' in s ||
			                        'MozTransition' in s ||
			                        'msTransition' in s ||
			                        'OTransition' in s;
			            s = null;
			            return r;
			        })();
			        
			        //检测浏览器是否支持webuploader
			        var isSupportUploader = (function(){
			        	if (!WebUploader.Uploader.support('flash') && WebUploader.browser.ie ) {
				            // flash 安装了但是版本过低。
				            if (flashVersion) {
				                (function(container) {
				                    window['expressinstallcallback'] = function( state ) {
				                        switch(state) {
				                            case 'Download.Cancelled':
				                                alert('您取消了更新！')
				                                break;
				
				                            case 'Download.Failed':
				                                alert('安装失败')
				                                break;
				
				                            default:
				                                alert('安装已成功，请刷新！');
				                                break;
				                        }
				                        delete window['expressinstallcallback'];
				                    };
				
				                    var swf = './expressInstall.swf';
				                    // insert flash object
				                    var html = '<object type="application/' +
				                            'x-shockwave-flash" data="' +  swf + '" ';
				
				                    if (WebUploader.browser.ie) {
				                        html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
				                    }
				
				                    html += 'width="100%" height="100%" style="outline:0">'  +
				                        '<param name="movie" value="' + swf + '" />' +
				                        '<param name="wmode" value="transparent" />' +
				                        '<param name="allowscriptaccess" value="always" />' +
				                    '</object>';
				
				                    container.html(html);
				
				                })($wrap);
				
				            // 压根就没有安转。
				            } else {
				                $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
				            }
				            return;
				        } else if (!WebUploader.Uploader.support()) {
				            alert( 'Web Uploader 不支持您的浏览器！');
				            return;
				        }
			        })();
			        /**检测浏览器过程结束*/
			        		
					webUpload.Uploader.register({
				        "before-send-file": "beforeSendFile",//整个文件上传前
				        "before-send": "beforeSend",  //每个分片上传前
				        "after-send-file": "afterSendFile",  //分片上传完毕
				  	},{
				  		beforeSendFile: beforeSendFile,
				  		beforeSend: beforeSend,
				  		afterSendFile: afterSendFile
				  	});
				  	
				  	//注册调用整个发送文件前事件
					var beforeSendFile = function(file){
						debugger
						/* var deferred = webUpload.Deferred();
			            //1、计算文件的唯一标记fileMd5，用于断点续传  如果.md5File(file)方法里只写一个file参数则计算MD5值会很慢 所以加了后面的参数：10*1024*1024
			            (new WebUploader.Uploader()).md5File(file, 0, 10 * 1024 * 1024).progress(function (percentage) {
			                $('#' + file.id).find('p.state').text('正在读取文件信息...');
			            }).then(function (val) {
			                $('#' + file.id).find("p.state").text("成功获取文件信息...");
			                fileMd5 = val;
			                //获取文件信息后进入下一步
			                deferred.resolve();
			            });
			            fileName = file.name; //为自定义参数文件名赋值
			            return deferred.promise(); */
					}
					//注册调用整个分块文件前事件
					var beforeSend = function(block){
						debugger
						/* var deferred = webUpload.Deferred();
			            $.ajax({
			                type: "POST",
			                url: '${adminPath}/demo/form/' + "mergeOrCheckChunks",  //ajax验证每一个分片
			                data: {
			                    param: "checkChunk",
			                    fileName: fileName,
			                    jindutiao: $("#jindutiao").val(),
			                    fileMd5: fileMd5,  //文件唯一标记
			                    chunk: block.chunk,  //当前分块下标
			                    chunkSize: block.end - block.start//当前分块大小
			                },
			                cache: false,
			                async: false,  // 同步
			                timeout: 1000, //todo 超时的话，只能认为该分片未上传过
			                //dataType:"json",
			                success: function (response) {
			                    var res = eval('(' + response + ')');
			                    if (res.ifExist) {
			                        //分块存在，跳过
			                        deferred.reject();
			                    } else {
			                        //分块不存在或不完整，重新发送该分块内容
			                        deferred.resolve();
			                    }
			                }
			            });
			            this.owner.options.formData.fileMd5 = fileMd5;
			            deferred.resolve();
			            return deferred.promise(); */
					}
					//注册调用文件成功后事件
					var afterSendFile = function(){
						debugger
						//如果分块上传成功，则通知后台合并分块
			            /* $.ajax({
			                type: "POST",
			                url: '${adminPath}/demo/form/'+"mergeOrCheckChunks",
			                data: {
			                    param: "mergeChunks",
			                    fileName: fileName,
			                    fileMd5: fileMd5
			                },
			                success: function (data) {
			                    count++; //每上传完成一个文件 count+1
			                    if (count <= filesArr.length - 1) {
			                        uploader.upload(filesArr[count].id);//上传文件列表中的下一个文件
			                    }
			                    //合并成功之后的操作
			                }
			            }); */
					}
					
					var uploader = webUpload.create({
						swf:'${staticPath}/vendors/webuploader/Uploader.swf',
						dnd:'#dndArea',//拖拽的容器
						disableGlobalDnd:true,
						paste:'#dndArea',
						pick:{
							id:'#filePicker',//主键名称
							label:'选择图片',//按钮名称，优先选择innerHTML
							innerHTML:'选择图片',//按钮名称
							multiple:true//开启多文件选择
						},
						server:'${adminPath}/demo/form/fileSave',
						auto:false,//自动上传
						prepareNextFile:false,
						chunked: true,//开启分片上传
						chunkSize:5242880,//分片大小
						chunkRetry:2,//网络问题出错，允许上传次数
						threads:3,//允许同时最大上传进程数
						formData:{},//文件上传请求的参数表
						fileVal:'file', //设置文件上传域的name
						method :'POST',//文件上传方式，POST或者GET
						sendAsBinary:false,//是否已二进制的流的方式发送文件
						fileNumLimit:3,//允许上传文件的总数量 
						fileSizeLimit:5242880,//验证文件总大小是否超出限制
						fileSingleSizeLimit:5242880,//验证单个文件大小是否超出限制
						duplicate:true,//根据文件名字、文件大小和最后修改时间来生成hash Key.
						//disableWidgets {String, Array} [可选] [默认值：undefined] 默认所有 Uploader.register 了的 widget 都会被加载，如果禁用某一部分，请通过此 option 指定黑名单
						accept:{
							title: '限制文件类型',
			    			extensions: 'gif,jpg,jpeg,bmp,png',
			    			mimeTypes: 'image/*'
						},
						thumb:thumb,
						compress:compress
					});
					
					var thumb = {
						width: 110,
					    height: 110,
					    // 图片质量，只有type为`image/jpeg`的时候才有效。
					    quality: 70,
					    // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
					    allowMagnify: true,
					    // 是否允许裁剪。
					    crop: true,
					    // 为空的话则保留原有图片格式。
					    // 否则强制转换成指定的类型。
					    type: 'image/jpeg'
					}
					
					var compress = {
						width: 1600,
					    height: 1600,
					    // 图片质量，只有type为`image/jpeg`的时候才有效。
					    quality: 90,
					    // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
					    allowMagnify: false,
					    // 是否允许裁剪。
					    crop: false,
					    // 是否保留头部meta信息。
					    preserveHeaders: true,
					    // 如果发现压缩后文件大小比原来还大，则使用原来图片
					    // 此属性可能会影响图片自动纠正功能
					    noCompressIfLarger: false,
					    // 单位字节，如果图片大小小于此值，不会采用压缩。
					    compressSize: 0
					}
					
			        // 添加“添加文件”的按钮，
			        uploader.addButton({
			            id: '#filePicker2',
			            label: '继续添加'
			        });
			
			        uploader.on('ready', function() {
			            window.uploader = uploader;
			        });
			
			        // 当有文件添加进来时执行，负责view的创建
			        function addFile( file ) {
			            var $li = $( '<li id="' + file.id + '">' +
			                    '<p class="title">' + file.name + '</p>' +
			                    '<p class="imgWrap"></p>'+
			                    '<p class="progress"><span></span></p>' +
			                    '</li>' ),
			
			                $btns = $('<div class="file-panel">' +
			                    '<span class="cancel">删除</span>' +
			                    '<span class="rotateRight">向右旋转</span>' +
			                    '<span class="rotateLeft">向左旋转</span></div>').appendTo( $li ),
			                $prgress = $li.find('p.progress span'),
			                $wrap = $li.find( 'p.imgWrap' ),
			                $info = $('<p class="error"></p>'),
			
			                showError = function( code ) {
			                    switch( code ) {
			                        case 'exceed_size':
			                            text = '文件大小超出';
			                            break;
			
			                        case 'interrupt':
			                            text = '上传暂停';
			                            break;
			
			                        default:
			                            text = '上传失败，请重试';
			                            break;
			                    }
			
			                    $info.text( text ).appendTo( $li );
			                };
			
			            if ( file.getStatus() === 'invalid' ) {
			                showError( file.statusText );
			            } else {
			                // @todo lazyload
			                $wrap.text( '预览中' );
			                uploader.makeThumb( file, function( error, src ) {
			                    var img;
			                    if ( error ) {
			                        $wrap.text( '不能预览' );
			                        return;
			                    }
			                    if( isSupportBase64 ) {
			                        img = $('<img src="'+src+'">');
			                        $wrap.empty().append( img );
			                    } else {
			                        $.ajax('../../server/preview.php', {
			                            method: 'POST',
			                            data: src,
			                            dataType:'json'
			                        }).done(function( response ) {
			                            if (response.result) {
			                                img = $('<img src="'+response.result+'">');
			                                $wrap.empty().append( img );
			                            } else {
			                                $wrap.text("预览出错");
			                            }
			                        });
			                    }
			                }, thumbnailWidth, thumbnailHeight );
			
			                percentages[ file.id ] = [ file.size, 0 ];
			                file.rotation = 0;
			            }
			
			            file.on('statuschange', function( cur, prev ) {
			            	debugger
			                if ( prev === 'progress' ) {
			                    $prgress.hide().width(0);
			                } else if ( prev === 'queued' ) {
			                    $li.off( 'mouseenter mouseleave' );
			                    $btns.remove();
			                }
			
			                // 成功
			                if ( cur === 'error' || cur === 'invalid' ) {
			                    console.log( file.statusText );
			                    showError( file.statusText );
			                    percentages[ file.id ][ 1 ] = 1;
			                } else if ( cur === 'interrupt' ) {
			                    showError( 'interrupt' );
			                } else if ( cur === 'queued' ) {
			                    percentages[ file.id ][ 1 ] = 0;
			                } else if ( cur === 'progress' ) {
			                    $info.remove();
			                    $prgress.css('display', 'block');
			                } else if ( cur === 'complete' ) {
			                    $li.append( '<span class="success"></span>' );
			                }
			
			                $li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
			            });
			
			            $li.on( 'mouseenter', function() {
			                $btns.stop().animate({height: 30});
			            });
			
			            $li.on( 'mouseleave', function() {
			                $btns.stop().animate({height: 0});
			            });
			
			            $btns.on( 'click', 'span', function() {
			                var index = $(this).index(),
			                    deg;
			
			                switch ( index ) {
			                    case 0:
			                        uploader.removeFile( file );
			                        return;
			
			                    case 1:
			                        file.rotation += 90;
			                        break;
			
			                    case 2:
			                        file.rotation -= 90;
			                        break;
			                }
			
			                if ( supportTransition ) {
			                    deg = 'rotate(' + file.rotation + 'deg)';
			                    $wrap.css({
			                        '-webkit-transform': deg,
			                        '-mos-transform': deg,
			                        '-o-transform': deg,
			                        'transform': deg
			                    });
			                } else {
			                    $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
			                    // use jquery animate to rotation
			                    // $({
			                    //     rotation: rotation
			                    // }).animate({
			                    //     rotation: file.rotation
			                    // }, {
			                    //     easing: 'linear',
			                    //     step: function( now ) {
			                    //         now = now * Math.PI / 180;
			
			                    //         var cos = Math.cos( now ),
			                    //             sin = Math.sin( now );
			
			                    //         $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')");
			                    //     }
			                    // });
			                }
			
			
			            });
			
			            $li.appendTo( $queue );
			        }
			
			        // 负责view的销毁
			        function removeFile( file ) {
			            var $li = $('#'+file.id);
			            delete percentages[ file.id ];
			            updateTotalProgress();
			            $li.off().find('.file-panel').off().end().remove();
			        }
					
					//更新总的进度条
			        function updateTotalProgress() {
			            var loaded = 0,
			                total = 0,
			                spans = $progress.children(),
			                percent;
			
			            $.each( percentages, function( k, v ) {
			                total += v[ 0 ];
			                loaded += v[ 0 ] * v[ 1 ];
			            } );
			
			            percent = total ? loaded / total : 0;
			
			
			            spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
			            spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
			            updateStatus();
			        }
			
					//更新文件状态
			        function updateStatus() {
			            var text = '', stats;
			
			            if ( state === 'ready' ) {
			                text = '选中' + fileCount + '张图片，共' +
			                        WebUploader.formatSize( fileSize ) + '。';
			            } else if ( state === 'confirm' ) {
			                stats = uploader.getStats();
			                if ( stats.uploadFailNum ) {
			                    text = '已成功上传' + stats.successNum+ '张照片至XX相册，'+
			                        stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
			                }
			
			            } else {
			                stats = uploader.getStats();
			                text = '共' + fileCount + '张（' +
			                        WebUploader.formatSize( fileSize )  +
			                        '），已上传' + stats.successNum + '张';
			
			                if ( stats.uploadFailNum ) {
			                    text += '，失败' + stats.uploadFailNum + '张';
			                }
			            }
			
			            $info.html( text );
			        }
			
					//设置文件状态
			        function setState( val ) {
			            var file, stats;
			
			            if ( val === state ) {
			                return;
			            }
			
			            $upload.removeClass( 'state-' + state );
			            $upload.addClass( 'state-' + val );
			            state = val;
			
			            switch ( state ) {
			                case 'pedding':
			                    $placeHolder.removeClass( 'element-invisible' );
			                    $queue.hide();
			                    $statusBar.addClass( 'element-invisible' );
			                    uploader.refresh();
			                    break;
			
			                case 'ready':
			                    $placeHolder.addClass( 'element-invisible' );
			                    $( '#filePicker2' ).removeClass( 'element-invisible');
			                    $queue.show();
			                    $statusBar.removeClass('element-invisible');
			                    uploader.refresh();
			                    break;
			
			                case 'uploading':
			                    $( '#filePicker2' ).addClass( 'element-invisible' );
			                    $progress.show();
			                    $upload.text( '暂停上传' );
			                    break;
			
			                case 'paused':
			                    $progress.show();
			                    $upload.text( '继续上传' );
			                    break;
			
			                case 'confirm':
			                    $progress.hide();
			                    $( '#filePicker2' ).removeClass( 'element-invisible' );
			                    $upload.text( '开始上传' );
			
			                    stats = uploader.getStats();
			                    if ( stats.successNum && !stats.uploadFailNum ) {
			                        setState( 'finish' );
			                        return;
			                    }
			                    break;
			                case 'finish':
			                    stats = uploader.getStats();
			                    if ( stats.successNum ) {
			                        alert( '上传成功' );
			                    } else {
			                        // 没有成功的图片，重设
			                        state = 'done';
			                        location.reload();
			                    }
			                    break;
			            }
			            updateStatus();
			        }
			        
			        //上传进度
			        uploader.onUploadProgress = function( file, percentage ) {
			            var $li = $('#'+file.id),
			                $percent = $li.find('.progress span');
			
			            $percent.css( 'width', percentage * 100 + '%' );
			            percentages[ file.id ][ 1 ] = percentage;
			            updateTotalProgress();
			        };
					
					//当文件被加入队列以后触发
			        uploader.onFileQueued = function( file ) {
						debugger
						filesArr.push(file);
			            fileCount++;
			            fileSize += file.size;
			            if ( fileCount === 1 ) {
			                $placeHolder.addClass( 'element-invisible' );
			                $statusBar.show();
			            }
			            addFile( file );
			            setState( 'ready' );
			            updateTotalProgress();
			        };
			
					//当文件被移除队列后触发
			        uploader.onFileDequeued = function( file ) {
			            fileCount--;
			            fileSize -= file.size;
			            if ( !fileCount ) {
			                setState( 'pedding' );
			            }
			            removeFile( file );
			            updateTotalProgress();
			
			        };
			
			        uploader.on( 'all', function( type ) {
			            var stats;
			            switch( type ) {
			                case 'uploadFinished'://当所有文件上传结束时触发
			                    setState( 'confirm' );
			                    break;
			
			                case 'startUpload'://当开始上传流程时触发
			                    setState( 'uploading' );
			                    break;
			
			                case 'stopUpload'://当开始上传流程暂停时触发
			                    setState( 'paused' );
			                    break;
			            }
			        });
			
					//文件错误
			        uploader.onError = function( code ) {
			            alert( 'Eroor: ' + code );
			        };
			
					//执行上传
			        $upload.on('click', function() {
			        	debugger
			            if ( $(this).hasClass( 'disabled' ) ) {
			                return false;
			            }
			            if ( state === 'ready' ) {
			                uploader.upload();
			            } else if ( state === 'paused' ) {
			                uploader.upload();
			            } else if ( state === 'uploading' ) {
			                uploader.stop();
			            }
			        });
			
			        $info.on( 'click', '.retry', function() {
			            uploader.retry();
			        } );
			
			        $info.on( 'click', '.ignore', function() {
			            alert( 'todo' );
			        } );
			
			        $upload.addClass( 'state-' + state );
			        updateTotalProgress();
				});
			})( jQuery );	
	</script>
</body>
</html>
